{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import numpy as np\n",
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {},
   "outputs": [],
   "source": [
    "file_names = os.listdir('digits/trainingDigits')\n",
    "label = '5_70.txt'.split('_')[0]\n",
    "txt = np.loadtxt('digits/trainingDigits/5_70.txt', dtype='str')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "metadata": {},
   "outputs": [],
   "source": [
    "txt = np.loadtxt('digits/trainingDigits/5_70.txt', dtype='str')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1024"
      ]
     },
     "execution_count": 52,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(''.join(txt))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "metadata": {},
   "outputs": [],
   "source": [
    "path = 'digits/trainingDigits'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "metadata": {},
   "outputs": [],
   "source": [
    "def getFileDF(path):\n",
    "    file_names = os.listdir(path)\n",
    "    labels = []\n",
    "    txts = []\n",
    "    for file_name in file_names:\n",
    "        label = file_name.split('_')[0]\n",
    "        file_path = path + '/' + file_name\n",
    "\n",
    "        txt = np.loadtxt(file_path, dtype='str')\n",
    "        labels.append(label)\n",
    "        txts.append(''.join(txt))\n",
    "    \n",
    "    return pd.DataFrame({\n",
    "        'txt': txts,\n",
    "        'label': labels\n",
    "    })"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "metadata": {},
   "outputs": [],
   "source": [
    "train = getFileDF('digits/trainingDigits')\n",
    "test = getFileDF('digits/testDigits')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>txt</th>\n",
       "      <th>label</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>0000000000000000000000000000000000000000000001...</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>0000000000000000011000000000000000000000000011...</td>\n",
       "      <td>7</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>0000000000000000000001111000000000000000000000...</td>\n",
       "      <td>9</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>0000000000000000011110000000000000000000000000...</td>\n",
       "      <td>4</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>0000000000011100000000000000000000000000000111...</td>\n",
       "      <td>6</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1929</th>\n",
       "      <td>0000000000000000000011111100000000000000000000...</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1930</th>\n",
       "      <td>0000000000000111110000000000000000000000000111...</td>\n",
       "      <td>9</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1931</th>\n",
       "      <td>0000000000111110000000000000000000000000011111...</td>\n",
       "      <td>9</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1932</th>\n",
       "      <td>0000000000000011111111111000000000000000001111...</td>\n",
       "      <td>5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1933</th>\n",
       "      <td>0000000001111000000000000000000000000000011111...</td>\n",
       "      <td>2</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>1934 rows × 2 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "                                                    txt label\n",
       "0     0000000000000000000000000000000000000000000001...     1\n",
       "1     0000000000000000011000000000000000000000000011...     7\n",
       "2     0000000000000000000001111000000000000000000000...     9\n",
       "3     0000000000000000011110000000000000000000000000...     4\n",
       "4     0000000000011100000000000000000000000000000111...     6\n",
       "...                                                 ...   ...\n",
       "1929  0000000000000000000011111100000000000000000000...     1\n",
       "1930  0000000000000111110000000000000000000000000111...     9\n",
       "1931  0000000000111110000000000000000000000000011111...     9\n",
       "1932  0000000000000011111111111000000000000000001111...     5\n",
       "1933  0000000001111000000000000000000000000000011111...     2\n",
       "\n",
       "[1934 rows x 2 columns]"
      ]
     },
     "execution_count": 56,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "train"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "metadata": {},
   "outputs": [],
   "source": [
    "def hamming(str1, str2):\n",
    "    len1 = len(str1)\n",
    "    len2 = len(str2)\n",
    "    if (len1 != len2):\n",
    "        return FileExistsError\n",
    "\n",
    "    distance = 0\n",
    "    for i in range(0, len1):\n",
    "        if (str1[i] != str2[i]):\n",
    "            distance +=1\n",
    "    \n",
    "    return distance"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "metadata": {},
   "outputs": [],
   "source": [
    "def hamm(str1, str2):\n",
    "    return sum ([a != b for (a,b) in zip(str1,str2)])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "metadata": {},
   "outputs": [],
   "source": [
    "def hammingDF(df, str2):\n",
    "    dists = []\n",
    "    for (i, row) in df.iterrows():\n",
    "        dist = hamm(row[0], str2)\n",
    "        dists.append(dist)\n",
    "    return pd.DataFrame({\n",
    "        'dist': dists,\n",
    "        'label': df['label']\n",
    "    })"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0"
      ]
     },
     "execution_count": 60,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "hamming(train.iloc[0,1], train.iloc[1929,1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'0000000000000000011000000000000000000000000011111111111110000000000000000111111111111111111000000000000011111111111111111111000000000000111111111111111111110000000000001111111111111111111100000000000001100000000111111110000000000000000000000000111111100000000000000000000000001111110000000000000000000000000011111100000000000000000000000001111110000000000000000000000000011111100000000000000000001111000111111000000000000000001111111111111000000000000000000011111111111110000000000000000000111111111111110000000000000000001111111111111100000000000000000001111111111111000000000000000000000001111111000000000000000000000000011111000000000000000000000000011111100000000000000000000000000111111000000000000000000000000011111110000000000000000000000000111111000000000000000000000000001111100000000000000000000000000011111000000000000000000000000001111110000000000000000000000000111111000000000000000000000000011111110000000000000000000000000111111100000000000000000000000000111100000000000000000000000000000010000000000000000000'"
      ]
     },
     "execution_count": 61,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "train.iloc[1,0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1"
      ]
     },
     "execution_count": 62,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "hamming(train.iloc[1,1], train.iloc[1929,1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "metadata": {},
   "outputs": [],
   "source": [
    "def knn(inX, df, k):\n",
    "    df_l = hammingDF(df, inX)\n",
    "    df_rank = df_l.sort_values(axis=0, by='dist', ascending=True)\n",
    "    return df_rank.iloc[:k].value_counts('label').index[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "metadata": {},
   "outputs": [],
   "source": [
    "def DigitsTest(train, test, k):\n",
    "    f_arr = []\n",
    "    for i, row in test.iterrows():\n",
    "        inX = row[0]\n",
    "        f_arr.append(knn(inX, train, k))\n",
    "    \n",
    "    df_res = pd.DataFrame({\n",
    "        'f_label': f_arr\n",
    "    })\n",
    "\n",
    "    return (df_res['f_label'] == test['label']).mean()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.9894291754756871"
      ]
     },
     "execution_count": 65,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "DigitsTest(train,test, 3)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.6"
  },
  "orig_nbformat": 4,
  "vscode": {
   "interpreter": {
    "hash": "d44d76ef8cbbc4331cecfe2e59228ac31ebb71026289858a116838be7168b60b"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
